﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Managements.Appointments;
using YAPACS.Organizations;

namespace YAPACS.RisServer.Controllers;
[Authorize]
public class AppointmentPlanController : AbpController
{
    private readonly ICurrentUserOrganization _currentUserOrganization;
    private readonly IRepository<AppointmentPlan> _appointmentPlanRepository;

    public AppointmentPlanController(IRepository<AppointmentPlan> appointmentPlanRepository, ICurrentUserOrganization currentUserOrganization)
    {
        _appointmentPlanRepository = appointmentPlanRepository;
        _currentUserOrganization = currentUserOrganization;
    }

    [HttpGet]
    [Route("api/appointmentplan/{deviceTypeId}/{date}")]
    public async Task<IActionResult> GetAppointmentPlans(Guid deviceTypeId,DateTime date)
    {
        var list= await _appointmentPlanRepository.GetListAsync(e => e.Department.Id == _currentUserOrganization.DepartmentId
         && e.Device.DeviceType.Id == deviceTypeId
         && e.Date.Value.Date == date.Date);

        var devices = list
            .GroupBy(a => a.Device)
            .Select(a => a.Key)
            .OrderBy(d => d.CompoundName)
            .ToList();

        var appointmentPlans = list
            .GroupBy(a => a.TimeInterval)
            .OrderBy(a => a.Key.Name)
            .ToDictionary(a => a.Key, a => a.ToList());

        List<Dictionary<string, object>> dynamicList = new List<Dictionary<string, object>>();
        foreach (var timeInterval in appointmentPlans.Keys)
        {
            dynamic row = new Dictionary<string, object>();

            row["时段"] = timeInterval.Name;

            foreach (var appointmentPlan in appointmentPlans[timeInterval])
            {
                //row[appointmentPlan.Device.CompoundName] = new { appointmentPlan.CurrentCount, appointmentPlan.MaxCount };
                row[appointmentPlan.Device.CompoundName] = $"{appointmentPlan.CurrentCount}/{appointmentPlan.MaxCount}";
                row["Id"] = appointmentPlan.Id;
            }

            dynamicList.Add(row);
        }
        return Ok(dynamicList);
    }


    [HttpGet]
    [Route("api/appointmentplan/{planId}")]
    public async Task<IActionResult> GetAppointmentPlan1(Guid planId)
    {
       var plan= await _appointmentPlanRepository.FirstOrDefaultAsync(e => e.Id == planId);
        if (plan != null)
        {
            return Ok(new
            {
                plan.Id,
                plan.Oid,
                plan.Date,
                Device =new
                {
                    plan.Device.CompoundName
                },
                TimeInterval=new
                {
                    plan.TimeInterval.Name,
                    plan.TimeInterval.Oid
                }
            });
        }
        return Ok();
    }
}
